#include "LoginDialog.h"
#include "ui_LoginDialog.h"
#include "ServerDialog.h"

LoginDialog::LoginDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::LoginDialog)
{
    ui->setupUi(this);
    //创建数据库
    createDB();
    createLoginTable();
}

LoginDialog::~LoginDialog()
{
    delete ui;
}
//登录
void LoginDialog::on_LoginButton_clicked()
{
    QSqlQuery query;
    QString id = ui->UserEdit->text();
    QString password = ui->PasswordEdit->text();
    QString str = QString("SELECT id,password FROM login WHERE id = %1 and password = %2").arg(id).arg(password);
    query.exec(str);
    if(!query.next())
    {
        QMessageBox msgBox(QMessageBox::Critical, windowTitle(), "账号或密码错误！", QMessageBox::Ok, this);
               msgBox.exec();
    }
    else
    {
         ServerDialog *rd = new ServerDialog ();
         rd->show();
         this->close();
    }
}
//创建数据库
void LoginDialog::createDB(void)
{
    db = QSqlDatabase::addDatabase("QSQLITE");
    //edb =  QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("Login.db");
    //db.setDatabaseName("Socket.db");
    if(false == db.open())
    {
        qDebug()<<db.lastError().text();
    }
    //if(false == edb.open())
    //{
    //    qDebug()<<edb.lastError().text();
    //}
}

//创建管理员登录数据表
void LoginDialog::createLoginTable(void)
{
    QSqlQuery query;
    QString str = QString ("CREATE TABLE login"
             "(id TEXT NOT NULL,"
             "password TEXT NOT NULL)");
    qDebug() << str;
    query.exec(str);
}
